package yxy.cherry.game.base.bean;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import org.redisson.api.RLock;
import org.redisson.api.RMap;
import org.redisson.api.RSet;

import yxy.apple.util.redisson.RedisConnection;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.game.base.redis.RedisManager;
import yxy.cherry.game.base.redis.RedisType;

/**
 * SDK 参数
 * 
 * @author Dell
 *
 */
public class SDKParm  {

	static public String getSdkparmvalue(SdkParmEnum sdkparm) {
		Map<String, String> sdkparms = all();
		
		if(sdkparms == null || sdkparms.size() == 0) {
			initSdkparm();
		}
		
		if(sdkparms.size() != 0 && sdkparms.containsKey(sdkparm.getSdkparmname())) {
			return sdkparms.get(sdkparm.getSdkparmname());
		}else {
			try {
				RMap<String, String> map = touch();
				if(!map.containsKey(sdkparm.getSdkparmname())) {
					touch().put(sdkparm.getSdkparmname(), sdkparm.getSdkparmvalue());					
				}
				
				return map.get(sdkparm.getSdkparmname());
			} catch (RedisException e) {
				e.printStackTrace();
			}
			return sdkparm.getSdkparmvalue();
		}
		
	}
	
	static public void initSdkparm() {
		SdkParmEnum[] sps = SdkParmEnum.values();
		for (SdkParmEnum sp : sps) {
			try {
				touch().put(sp.getSdkparmname(), sp.getSdkparmvalue());
			} catch (RedisException e) {
				e.printStackTrace();
			}
		}
	}
	
	// redis==========================================================================

	static private RMap<String, String> touch() throws RedisException {
		return RedisManager.client(RedisManager.getInstance().getConnection(RedisType.REDIS_USER)).getMap(key());
	}

	static public Map<String, String> all() {
		try {
			Map<String, String> sdkparms = touch().readAllMap();
			return sdkparms;
		} catch (RedisException e) {
		}
		return new HashMap<>();
	}
	
	static public String key() {
		return "sdkparm";
	}

	static public RSet<String> touch(RedisConnection redis) throws RedisException {
		if (redis.ready()) {
			try {
				return redis.client().getSet(key());
			} catch (Exception e) {
				throw new RedisException(e);
			}
		} else {
			throw new RedisException("无可用Redis连接!");
		}
	}

	static public Collection<String> all(RedisConnection redis) {
		try {
			return touch(redis).readAll();
		} catch (RedisException e) {
			e.printStackTrace();
		}
		return new HashSet<>();
	}

	static private RLock lock(RedisConnection redis) {
		return redis.client().getLock(key() + "_lock");
	}
}
